package com.aaa.backsystem.controller;


import com.aaa.backsystem.aop.SaveOrUpdateEntityAnn;
import com.aaa.backsystem.entity.*;
import com.aaa.backsystem.service.DeptService;
import com.aaa.backsystem.service.RoleService;
import com.aaa.backsystem.service.UserService;
import com.aaa.backsystem.service.impl.FileUploadService;
import com.aaa.backsystem.util.MyConstants;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户信息表 前端控制器
 * </p>
 *
 * @author gyc
 * @since 2020-07-18
 */
@Controller
@RequestMapping("/user")
public class UserController extends BaseController {

    @Autowired
    private FileUploadService fileUploadService;
    @Autowired
    private UserService userService;
    @Autowired
    private DeptService deptService;
    @Autowired
    private RoleService roleService;

    /**
     * 获取部门信息，角色信息，填充下拉列表
     * 页面跳转
     *
     * @return
     */
    @RequestMapping("/toShowUser")
    public String toShowUser(Model model) {
        Wrapper wrapper = new EntityWrapper();
        wrapper.eq("del_flag", 0);

        List deptList = deptService.selectList(wrapper);
        List roleList = roleService.selectList(wrapper);

        model.addAttribute("deptList", deptList);
        model.addAttribute("roleList", roleList);

        return "user/showUser";
    }

    /**
     * 获取用户信息（包含部门信息），分页等操作
     *
     * @param page
     * @param limit
     * @param searchLoginName
     * @param searchUserName
     * @param searchPhoneNumber
     * @return
     */
    @GetMapping("/userList")
    @ResponseBody
    public LayuiTable userList(Integer page, Integer limit, String searchLoginName, String searchUserName, String searchPhoneNumber) {
        LayuiTable table = new LayuiTable();

        Wrapper wrapper = new EntityWrapper();
        //多条件查询所需要的集合
        Map<String, Object> condition = new HashMap(16);

        if (null != searchLoginName && !"".equals(searchLoginName)) {
            wrapper.like("login_name", searchLoginName);
            condition.put("login_name", searchLoginName);
        }
        if (null != searchUserName && !"".equals(searchUserName)) {
            wrapper.like("user_name", searchUserName);
            condition.put("user_name", searchUserName);
        }
        if (null != searchPhoneNumber && !"".equals(searchPhoneNumber)) {
            wrapper.like("phonenumber", searchPhoneNumber);
            condition.put("phonenumber", searchPhoneNumber);
        }
        //存在的用户
        wrapper.eq("del_flag", 0);
        condition.put("del_flag", 0);

        //查询存在用户的条数
        int userListCount = userService.selectCount(wrapper);

        //如果表中没有数据。则不进行分页查询
        if (userListCount > 0) {

            //分页
            Page<UserVo> pageInfo = new Page(page, limit);

            List<UserVo> userVoList = userService.selectUserVoList(pageInfo, condition);
            //从分页结果中提取list集合
            table.setCode(MyConstants.OPERATION_SUCCESS_CODE);
            table.setMsg(MyConstants.OPERATION_SUCCESS_MESSAGE);
            table.setData(userVoList);
            table.setCount(userListCount);
        }
        return table;
    }

    /**
     * 单行删除(逻辑删除)
     *
     * @param user
     * @return
     */
    @DeleteMapping("/deleteUser")
    @ResponseBody
    public Result deleteUser(User user) {
        try {
            user.setDelFlag("2");
            boolean flag = userService.updateById(user);

            return success();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return error();
    }

    /**
     * 多行删除（逻辑删除）
     *
     * @param userList
     * @return
     */
    @RequestMapping("/deleteBatchUser")
    @ResponseBody
    public Result deleteBatchUser(@RequestBody List<User> userList) {
        List<User> userListNew = new ArrayList<>();
        for (User user : userList) {
            User userNew = new User();
            userNew.setDelFlag("2");
            userNew.setUserId(user.getUserId());
            userListNew.add(userNew);
        }
        boolean flag = userService.updateBatchById(userListNew);
        if (flag) {
            return success();
        } else {
            return error();
        }
    }

    /**
     * 根据用户id查询角色
     *
     * @param userId
     * @return
     */
    @RequestMapping("/getRoleCheckByUserId")
    @ResponseBody
    public Result getRoleCheckByUserId(Integer userId) {
        List<Role> roleUserList = roleService.selectListByUserId(userId);
        List<Role> roleList = roleService.selectList(null);

        Map map = new HashMap();
        for (Role role : roleList) {
            //判断集合包含对象，必须重写equals和hashcode方法
            if (roleUserList.contains(role)) {
                map.put(role.getRoleKey(), true);
            } else {
                map.put(role.getRoleKey(), false);
            }
        }
        return success(map);
    }

    /**
     * 修改用户
     *
     * @return
     */
    @RequestMapping("/updateUser")
    @ResponseBody
    @SaveOrUpdateEntityAnn(entityClass = User.class)
    public Result updateUser(User user) {
        boolean update = userService.updateUserAndSalt(user);
        if (update) {
            return success();
        } else {
            return error();
        }
    }

    /**
     * 保存用户
     *
     * @return
     */
    @RequestMapping("/saveUser")
    @ResponseBody
    @SaveOrUpdateEntityAnn(entityClass = User.class)
    public Result saveUser(User user) {
        boolean insert = userService.saveUserAndSalt(user);
        if (insert) {
            return success();
        } else {
            return error();
        }
    }

    /**
     * 重置密码
     *
     * @param user
     * @return
     */
    @RequestMapping("/resetPassword")
    @ResponseBody
    public Result resetPassword(User user) {
        boolean flag = userService.resetPassword(user);
        if (flag) {
            return success();
        } else {
            return error();
        }
    }

    /**
     * 判断用户名是否存在，存在的话返回false，不存在返回true
     *
     * @param loginName
     * @return
     */
    @RequestMapping("/checkUserName")
    @ResponseBody
    public Result checkUserName(String loginName) {
        Wrapper<User> wrapper = new EntityWrapper<>();
        User user = userService.selectOne(wrapper.eq("login_name", loginName));
        if (user != null) {
            return error(MyConstants.OPERATION_FAIL_CODE, loginName + "已经被占用");
        }
        return super.success();
    }

    @RequestMapping("/Wx")
    @ResponseBody
    public User queryUser(String token, HttpServletResponse response) {
        User user = new User();
        user.setLoginName("admin");
        user.setPassword("123456");
        return user;

    }

    /**
     * 头像上传到oss
     */
    @RequestMapping("/uploadAvatar")
    @ResponseBody
    public FileUploadResult upload(@RequestParam("file") MultipartFile uploadFile) throws Exception {
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        FileUploadResult  result = fileUploadService.upload(uploadFile);
        String url = "https://" + result.getName();
        User user1 = new User();
        user1.setUserId(user.getUserId());
        user1.setAvatar(url);
        userService.updateById(user1);
        return result;
    }

    /**
     * 根据id查询用户信息
     * @return
     */
    @RequestMapping("/getUserById")
    @ResponseBody
    public Result getUserById() {
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        User user1 = userService.selectById(user.getUserId());
        Result<User> result = new Result<>();
        result.setData(user1);
        result.setCode(MyConstants.OPERATION_SUCCESS_CODE);
        result.setMsg(MyConstants.OPERATION_SUCCESS_MESSAGE);
        return result;
    }

    /**
     * 个人资料修改
     * @return
     */
    @RequestMapping("/update")
    @ResponseBody
    public Result update(@RequestBody User user) {
        boolean update = userService.updateUserAndSalt(user);
        if (update) {
            return success();
        } else {
            return error();
        }
    }

}

